<template>
  <div class="resizable-pane" :style="{ width: containerWidth + 'px' }" ref="containerRef">
    <div class="code-pane" :style="{ width: codeWidth + 'px' }">
      <slot name="code"></slot>
    </div>
    <div class="resize-bar" @mousedown="handleMouseDown"></div>
    <div class="render-pane">
      <slot name="render"></slot>
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted, onUnmounted, nextTick } from 'vue';

  const props = defineProps({
    defaultCodeWidth: {
      type: Number,
      default: 400,
    },
    minCodeWidth: {
      type: Number,
      default: 0,
    },
  })

  const startX = ref(null);
  const containerWidth = ref(null);
  const codeWidth = ref(props.defaultCodeWidth);
  const containerRef = ref(null)

  onMounted(() => {
    nextTick(() => {
      calculateContainerWidth();
    });
    containerRef.value.addEventListener('mousemove', handleMouseMove);
    containerRef.value.addEventListener('mouseup', handleMouseUp);
  })

  const calculateContainerWidth = () => {
    containerWidth.value = containerRef.value.clientWidth;
  }
  const handleMouseDown = (event) => {
    startX.value = event.clientX;
  }
  const handleMouseMove = (event) => {
    if (startX.value) {
      const offsetX = event.clientX - startX.value;
      const newCodeWidth = codeWidth.value + offsetX;
      if (newCodeWidth >= props.minCodeWidth && newCodeWidth <= containerWidth.value - props.minCodeWidth) {
        codeWidth.value = newCodeWidth;
      }
      startX.value = event.clientX;
    }
  }

  const handleMouseUp = () => {
    startX.value = null;
  }

  onUnmounted(() => {
    containerRef.value.removeEventListener('mousemove', handleMouseMove);
    containerRef.value.removeEventListener('mouseup', handleMouseUp);
  })
</script>

<style scoped>
.resizable-pane {
  display: flex;
  height: 100%;
  overflow: hidden;
}

.code-pane {
  flex: 0 0 auto;
  overflow-x: hidden;
  overflow-y: auto;
  border-right: 1px solid #ebeef5;
}

.resize-bar {
  width: 6px;
  cursor: ew-resize;
}

.render-pane {
  flex: 1 1 auto;
  overflow: auto;
}
</style>
